package com.github.xzb617.security.token;

import cn.hutool.core.date.DateUtil;
import com.github.xzb617.domain.entity.User;
import com.github.xzb617.props.SecurityProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * 令牌管理器
 * @author xzb617
 */
@Component("tokenManager")
public class TokenManager {

    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 过期时间为: 6小时
     */
    private final static int EXPIRE_TIME = 60*60*6;

    private final SecurityProperties securityProperties;

    public TokenManager(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    /**
     * 创建令牌
     * @param user
     * @return
     */
    public String createToken(User user) {
        // 生成访问令牌
        JwtClaims accessClaims = this.buildClaims(user);
        return JJwt.createToken(accessClaims, user.getId(), user.getRole(), this.securityProperties.getTokenSecret());
    }

    /**
     * 刷新令牌
     * @param user
     * @return
     */
    public String refreshToken(User user) {
        return this.createToken(user);
    }


    private JwtClaims buildClaims(User user) {
        // 计算时间
        Date issuedAt = new Date();
        Date expiration = DateUtil.offsetSecond(issuedAt, EXPIRE_TIME);
        return new JwtClaims(
                UUID.randomUUID().toString(),
                user.getUsername(),
                applicationName,
                issuedAt,
                expiration
        );
    }

}
